﻿using Microsoft.EntityFrameworkCore;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using MESData.Infrastucture.Impement;
using MESData.Infrastucture.Interface;
using MESData.Infrastucture;
using ConsoleApi.AllError;
using ConsoleApi.Services.Logins;

namespace ConsoleApi.Extensions
{
    /// <summary>
    /// 扩展方法 静态类 静态方法 this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //注册全局异常处理
            builder.Services.AddControllers(x => x.Filters.Add<GloabIExcptionfilter>());

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "ConsoleApi.xml", true));
            
            // 优化：使用DbContext池提高性能
            builder.Services.AddDbContextPool<MyDbcontext>(x =>
            {
                x.UseMySql(builder.Configuration.GetConnectionString("db"), new MySqlServerVersion("5.7"), options =>
                {
                                    // 配置连接池和并发查询选项
                options.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                // 配置批处理大小
                options.MaxBatchSize(100);
                });
                
                // 启用服务提供程序缓存
                x.EnableServiceProviderCaching();
                
                // 启用查询编译缓存（EF Core 8.0+）
                // x.EnableQueryCompilationCache();
                
                // 配置查询跟踪行为（全局设置为非跟踪，需要时再启用）
                x.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
                
                // 启用敏感数据日志记录（仅在开发环境）
                if (builder.Environment.IsDevelopment())
                {
                    x.EnableSensitiveDataLogging();
                    x.LogTo(Console.WriteLine, LogLevel.Information);
                }
            });

            //配置Base模块
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            builder.Services.AddScoped<IAuthService, AuthService>();
            builder.Services.AddScoped<ConsoleApi.Services.Console.IConsoleService, ConsoleApi.Services.Console.ConsoleService>();
            
            // 优化：注册查询优化服务
            builder.Services.AddScoped<ConsoleApi.Services.Console.QueryOptimizationService>();
            

            
            // 优化：注册内存缓存服务
            builder.Services.AddMemoryCache();
            builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
                };
            });

            return builder;
        }
    }
}
